import xml.dom.minidom
import subprocess
from xml.dom.minidom import Node
 
HexCharacters = "0123456789abcdef"
#helper: Encode URLs containing special characters
def UrlEncode(s):
	r = ''
	for c in s:
		o = ord(c)
		if (o >= 48 and o <= 57) or \
			(o >= 97 and o <= 122) or \
			(o >= 65 and o <= 90) or \
			o == 36 or o == 45 or o == 95 or \
			o == 46 or o == 43 or o == 33 or \
			o == 42 or o == 39 or o == 40 or \
			o == 41 or o == 44:
			r += c
		else:
			r += '%' + CleanCharHex(c)
	return r

def CleanCharHex(c):
	o = ord(c)
	r = HexCharacters[o / 16]
	r += HexCharacters[o % 16]
	return r

# Extract site list and return them.
def extractSites(myDom):
	resources = myDom.getElementsByTagName("resources");

	urls = [];
	for nodes in resources.item(0).childNodes:
		if nodes.nodeType == Node.ELEMENT_NODE:
			for iter in nodes.childNodes:
				#print iter.data;
				str = "\"";
				str += iter.data.lstrip();
				str = str.rstrip();
				str = str + "\"";
				#print UrlEncode(str);
				#print str;
				#urls.append(iter.data);
				#urls.append(UrlEncode(str));
				urls.append(str);
	return urls;

# Extract edges list and their respective operations.
def extractEdges(myDom):
	edges = myDom.getElementsByTagName("edges");
	
	edgesList = [];
	i = 0;
	
	for edgeNodes in edges.item(0).childNodes:
		if edgeNodes.nodeType == Node.ELEMENT_NODE:
			edgesList.append([]);
			for iter in edgeNodes.childNodes:
				if iter.nodeName == "link":
					for links in iter.childNodes:
						n = links.data.split(',');
						edgesList[i].append ( int(n[0]) );
						edgesList[i].append ( int(n[1]) );
				elif iter.nodeName == "cause":
					for causes in iter.childNodes:
						edgesList[i].append(causes.data);
	
			i = i+1;
	return edgesList;

def generateGraph(xmlStr):
	#doc = xml.dom.minidom.parse("output.xml");
	doc = xml.dom.minidom.parseString(xmlStr);
	landingSite = doc.getElementsByTagName("landingsite");
	landingSite = landingSite.item(0).firstChild.data;

	urls = extractSites(doc);
	edgesList = extractEdges(doc);
	
    #generate a DOT format file using urls and edgesList
	f = open("output.gv", "w")
	f.write("digraph phoneyCoutput { \nlabel = \"Landing Site : ");
	f.write(landingSite);
	f.write("\";\n\nnode [shape=circle]; ");
	
	for j in range(0, len(urls)):
		f.write(urls[j]);
		f.write("; ");
	
	f.write("\n\n");
	
	for k in range(0,len(edgesList)):
		f.write(urls[edgesList[k][0] - 1]);
		f.write("->");
		f.write(urls[edgesList[k][1] - 1]);
		if len(edgesList[k]) == 3:
			f.write(" [ label = \"");
			f.write(edgesList[k][2]);
			f.write("\" ] ");
	
		f.write(";\n");
	
	f.write("\n}");
	print "DOT format file created. Filename: output.gv"

	subprocess.Popen([r"dot","-Tpng", "-ooutput.png", "output.gv"])
	print "PNG file created out of .gv file. Filename: output.png"

	#for index in range(len(urls)):
	#	print urls[index];
	
